#include "SelectExternalTagWindow.h"
#include "ui_SelectExternalTagWindow.h"
#include <QFileDialog>
#include "swf/SWFDecoder.h"
#include "swf/abc/AS3Model.h"
#include "model/SWFTreeModel.h"
#include "swf/SWFTagWrapper.h"

SelectExternalTagWindow::SelectExternalTagWindow(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SelectExternalTagWindow)
{
    ui->setupUi(this);

	QString fileName = QFileDialog::getOpenFileName(this, "Select SWF", "", "SWF(*.swf)");
	if (!QFile::exists(fileName))
		return;//TODO: message box

	SWFDecoder decoder;
	SWF* swf = decoder.decode(fileName.toStdString());

	_swfObjectModel = new SWFTreeModel();
	AS3SWF* as3swf = new AS3SWF(swf, QFileInfo(fileName));
	SWFItem* item = new SWFItem(as3swf);
	_swfObjectModel->appendRow(item);

	ui->treeView->setModel(_swfObjectModel);
}

SelectExternalTagWindow::~SelectExternalTagWindow()
{
    delete ui;
}

void SelectExternalTagWindow::accept()
{
	auto index = ui->treeView->currentIndex();
	auto item = _swfObjectModel->itemFromIndex(index);
	if (item)
	{
		SWFTagWrapper* w = (SWFTagWrapper*) item->getUserData();
		this->done((int)(w->getTag()));
	}
}
